package com.yaopaikeji.service.impl;

import com.yaopaikeji.constants.Constants;
import com.yaopaikeji.dao.UserDao;
import com.yaopaikeji.exception.AuthenticationException;
import com.yaopaikeji.exception.LoginFailException;
import com.yaopaikeji.model.User;
import com.yaopaikeji.service.UserService;
import com.yaopaikeji.util.LoginHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Override
    public User login(String loginId, String pass) {
        User user = userDao.findByLoginId(loginId);

        if (user == null || !user.getPass().equals(pass)) {

            throw new LoginFailException(Constants.LOGIN_FAIL_ERROR);
        }

        LoginHelper.login(user);

        return user;
    }

    @Override
    public void logout() {

        LoginHelper.removeLoginInfo();
    }

    @Override
    public boolean isLogined() {

        return LoginHelper.isLogined();
    }

    @Override
    public boolean checkLoginId(String loginId) {

        if (StringUtils.isBlank(loginId))
            return false;

        return userDao.isLoginIdExists(loginId);
    }

    @Override
    public User getCurrentUser() {

        return LoginHelper.getCurrentUser();
    }

    @Override
    public boolean isAdmin() {
        return LoginHelper.isAdmin();
    }

    @Override
    public boolean isRoot() {
        return LoginHelper.isRoot();
    }

    @Override
    public List<User> getAllUsers() {
        return userDao.findAll();
    }

    @Override
    public User updateUserInfo(User user) {

        User cUser = getCurrentUser();

        if (cUser != null) {

            if(user.getId() != cUser.getId()){//更新的用户信息不是当前登陆人的信息

                if(Constants.ROLE_ROOT_NAME.equals(cUser.getRoleInfo().getRoleName())){
                    //如果是root，可以修改任何人的
                    return userDao.updateUser(user);
                } else{

                    throw new AuthenticationException("权限不足");
                }
            } else {

                LoginHelper.updateCurrentUser(user);//更新session中的user信息
                return userDao.updateUser(user);
            }
        }

        //如果没有登陆
        throw new AuthenticationException("需要登陆");
    }

    @Override
    public boolean deleteUser(User user) {
        return userDao.deleteUserById(user.getId());
    }

    @Override
    public boolean activeUser(User user) {
        return userDao.updateIsActiveById(user.getId(), Constants.ACTIVE);
    }

    @Override
    public boolean freezeUser(User user) {
        return userDao.updateIsActiveById(user.getId(), Constants.INACTIVE);
    }

    @Override
    public User addNew(User user) {
        return userDao.saveUser(user);
    }
}
